# -*- coding: utf-8 -*-
from api import api, GlobalError
from flask import jsonify, request
from model.good import Good
from model.merchant import Merchant
from werkzeug.exceptions import NotFound


@api.route('/merchants', methods=['GET'])
def get_all_merchants():
    '''
## 分页获取商家

    GET /api/merchants

Parameters:

* `sort` (int, optional) - 排序方式，0表示按入驻时间排，1表示按照销量排，默认为0
* `skip` (int, optional) - 默认为0
* `total` (int, optional) - 默认为20

Return:

* `merchants` (list of dict)
    * `merchantId` (string)
    * `avatarUrl` (string)
    * `createTime` (long)
    * `description` (string)
    * `name` (string)
    * `phone` (int)
    * `sales` (int)
    * `goodImage` (list of string)
    '''
    sort_way = request.args.get('sort', 0, type=int)
    if sort_way == 0:
        sort_field = (Merchant.Field.createTime, 1)
    elif sort_way == 1:
        sort_field = (Merchant.Field.sales, -1)
    else:
        return jsonify(stat=0, **GlobalError.PARAMETERS_INVALID), 403
    skip = request.args.get('skip', 0, type=int)
    total = request.args.get('total', 20, type=int)
    merchants = Merchant.find({}, sort=[sort_field], skip=skip, limit=total)

    for merchant in merchants:
        good_ids = merchant.get(Merchant.Field.goodList)
        goods = Good.find({
            Good.Field._id: {
                '$in': good_ids
            }
        }, sort=[(Good.Field.updateTime, -1)], skip=0, limit=4)
        merchant['goodImage'] = []
        for good in goods:
            merchant['goodImage'].append(good.get(Good.Field.images)[0])
        merchant['merchantId'] = merchant['_id']
        del merchant['_id']
        del merchant[Merchant.Field.goodList]

    return jsonify(stat=1, merchants=merchants)


@api.route('/merchant/<merchant_id>', methods=['GET'])
def get_merchant(merchant_id):
    '''
## 获取商家详情

    GET /api/merchant/<merchant_id>

Return:

* `merchant` (dict)
    * `avatarUrl` (string)
    * `createTime` (long)
    * `description` (string)
    * `name` (string)
    * `phone` (int)
    * `sales` (int)
    '''
    try:
        merchant = Merchant.get({
            Merchant.Field._id: merchant_id
        }, [
            Merchant.Field.avatarUrl,
            Merchant.Field.createTime,
            Merchant.Field.description,
            Merchant.Field.name,
            Merchant.Field.phone,
            Merchant.Field.sales
        ])
    except NotFound:
        return jsonify(stat=0, **GlobalError.PARAMETERS_INVALID), 403

    return jsonify(stat=1, merchant=merchant.data)


@api.route('/merchant/<merchant_id>/goods', methods=['GET'])
def get_merchant_goods(merchant_id):
    '''
## 分页获取商家商品

    GET /api/merchant/<merchant_id>/goods

Parameters:

* `skip` (int, optional) - 默认为0
* `total` (int, optional) - 默认为20

Return:

* `goods` (list of dict)
    * `goodId` (string)
    * `discount` (double) - 折扣，真实价格 = 原价格 * 折扣
    * `image` (string)
    * `price` (double)
    * `title` (string)
    * `updateTime` (long)
    '''
    try:
        merchant = Merchant.get({
            Merchant.Field._id: merchant_id
        })
    except NotFound:
        return jsonify(stat=0, **GlobalError.PARAMETERS_INVALID), 403
    skip = request.args.get('skip', 0, type=int)
    total = request.args.get('total', 20, type=int)
    good_ids = merchant.data.get(Merchant.Field.goodList)[skip: skip + total]
    goods = []
    for good_id in good_ids:
        good = Good.get({
            Good.Field._id: good_id
        }, [
            Good.Field.discount,
            Good.Field.images,
            Good.Field.price,
            Good.Field.title,
            Good.Field.updateTime
        ])
        good.data['image'] = good.data.get(Good.Field.images)[0]
        del good.data[Good.Field.images]
        good.data['goodId'] = good.data.get(Good.Field._id)
        del good.data[Good.Field._id]
        goods.append(good.data)
    return jsonify(stat=1, goods=goods)
